package com.myhome.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Set;

/**
 * @Author QYiXin
 * @Date 2021 10 05 10 41
 **/
@Component
public class JwtGlobalFilter implements GlobalFilter, Ordered {
    @Value("${noJwtUrls:/admin/login,/user/gt/register,/user/login,/user/users/register,/user/users/setPassword,/user/sms/sendTo}")
    private Set<String> noJwtUrls;
    @Autowired
    StringRedisTemplate template;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();
        if (noJwtUrls.contains(path)) {
            return chain.filter(exchange);
        }
        String authorization = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION).replace("bearer ","");
        if (authorization == null||authorization.trim()=="") {
            return tokenResult(exchange);
        }
        boolean isExist = template.hasKey(authorization);
        if (!isExist) {
            tokenResult(exchange);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> tokenResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject object = new JSONObject();
        object.put("error", "未登录");
        object.put("msg", "token为空");
        DataBuffer buffer = response.bufferFactory().wrap(object.toJSONString().getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Flux.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
